/**
 * PageInfo.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013年8月15日
 */
package com.pshare.framework.page;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页信息对象
 */
public class PageInfo<T> implements java.io.Serializable {

	private static final long serialVersionUID = 1L;
	public final static int NO_ROW_OFFSET = 0;
	private final static int NO_ROW_LIMIT = 20;

	private int pageNo;
	private int offset;
	private int limit;
	private long totalCount = 0;
	private long totalPage = 0;

	/**
	 * 当前页中存放的记录,类型一般为List.
	 */
	protected List<T> list = new ArrayList<T>();

	/** 默认构造函数 */
	public PageInfo() {
		this.offset = NO_ROW_OFFSET;
		this.limit = NO_ROW_LIMIT;
	}

	public PageInfo(Integer pageNo) {
		if (pageNo == null || pageNo < 1)
			pageNo = 1;
		this.setPageNo(pageNo);
		this.limit = NO_ROW_LIMIT;
		this.offset = (pageNo - 1) * limit;
	}

	/** 构造函数 */
	public PageInfo(Integer pageNo, int pageSize) {
		if (pageNo == null || pageNo < 1)
			pageNo = 1;
		this.setPageNo(pageNo);
		this.limit = pageSize;
		this.offset = (pageNo - 1) * limit;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
		calcTotalPage(totalCount, limit);
	}

	public long getTotalCount() {
		return totalCount;
	}

	private void calcTotalPage(long totalCount, int pageSize) {
		if (pageSize != 0) {
			totalPage = totalCount / pageSize;
			if (totalCount % pageSize > 0) {
				totalPage++;
			}
		}
	}

	/**
	 * 是否还有上一页
	 * @return
	 */
	public boolean hasPre() {
		return (pageNo > 1);
	}

	/**
	 * 是否还有下一页.
	 */
	public boolean hasNext() {
		return (pageNo < totalPage);
	}

	/**
	 * 取得上页的页号, 序号从1开始. 当前页为首页时返回首页序号.
	 */
	public int getPrePage() {
		if (hasPre()) {
			return pageNo - 1;
		} else {
			return pageNo;
		}
	}

	/**
	 * 取得下页的页号, 序号从1开始. 当前页为尾页时仍返回尾页序号.
	 */
	public int getNextPage() {
		if (hasNext()) {
			return pageNo + 1;
		} else {
			return pageNo;
		}
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		if (pageNo > 0) {
			this.pageNo = pageNo;
		}
	}

	public int readOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int readLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public void setTotalPage(long totalPage) {
		this.totalPage = totalPage;
	}

	public long getTotalPage() {
		return totalPage;
	}
	
	public int getCurrentCount() {
		return list.size();
	}

	public List<T> getList() {
		return list;
	}

	public void setList(List<T> list) {
		if (list != null)
			this.list = list;
	}

}
